<script lang="ts" setup>
import type {DailySuggestItem, GuessAnimalItem} from "@/types/home";
import {ImgErrorType} from "@/enum/imgErrorType";
import type {ImgError} from "@/types/error";
import {computed, ref, watch} from "vue";
import {onLoad} from "@dcloudio/uni-app";
import type {AnimalSortType} from "@/enum/animalSortType";
import {useIndexListModelStore} from "@/stores/indexListModel";
import {useUserStore} from "@/stores/user";
import {addFavApi} from "@/api/detail";

const {safeAreaInsets, windowWidth} = uni.getSystemInfoSync();

// 下拉刷新
onLoad(() => {
  uni.stopPullDownRefresh()
})
const props = defineProps<{
  animalsList: DailySuggestItem[] // 动物列表
  top?: number  // 顶部外边距，距离单位px
  showName?: boolean // 是否显示名字,
  type?: AnimalSortType // 当前列表排序0、全部 1、热度 2、评分
  useWaterfall?: boolean // 是否使用瀑布流布局
  hideText?: boolean // 是否显示文字介绍（只有瀑布流时有效）
  showPageView?: boolean // 是否显示浏览量
}>()

const list = ref<DailySuggestItem[]>(props.animalsList || [])
// 图片预览
const finishImgList = ref<boolean[]>(new Array(props.animalsList?.length).fill(false))
const onFinishLoad = (index: number) => {
  finishImgList.value[index] = true
}

/**
 * 点击跳转详情页
 * @param id 对应id
 * @param type 类型 0-详细 1-图集
 * @param cover
 */
const goDetail = (id: string, type?: 0 | 1, cover?: string) => {
  if (Number(type) === 1) {
    // 获取图片应占高度
    uni.getImageInfo({
      src: cover!,
      success: (res) => {
        const height = windowWidth / res.width * res.height
        uni.navigateTo({
          url: '/subPkg/picDetail/picDetail?id=' + id + '&cover=' + cover + '&height=' + height
        })
      },
      fail: (err) => {
        uni.navigateTo({
          url: '/subPkg/picDetail/picDetail?id=' + id
        })
      }
    })
    return
  }

  uni.navigateTo({
    url: `/subPkg/detail/detail?id=${id}`
  })
}

/*异常处理*/
const emit = defineEmits<{
  imgError: [erroImg: ImgError]
}>()

//图片拿到链接但加载失败
const errorType = ImgErrorType
/**
 * 图片加载失败
 * @param index 失败索引
 * @param type 失败类型
 */
const onImgError = (index: number, type: ImgErrorType) => {
  emit('imgError', {index, type, secondaryType: props.type})
}
const indexListModelStore = useIndexListModelStore();
const onLongPress = (animal: GuessAnimalItem) => {
  console.log('长按' + animal.id)
  /*  if (indexListModelStore.graphicModel) {
      uni.previewImage({
        urls: [animal.img]
      })
    }*/
}

/*-------------瀑布流-------------*/
/*const list1 = ref<DailySuggestItem[]>([])
const list2 = ref<DailySuggestItem[]>([])*/
const list1 = computed(() => {
  return list.value?.filter((item, index) => item.list === 1)
})// 瀑布流第一列数据
const list2 = computed(() => {
  return list.value?.filter((item, index) => item.list == 2)
})// 瀑布流第二列数据
const leftGap = ref(10)
const rightGap = ref(10)
const columnGap = ref(10)
// const imageStyle=computed((item:any)=>{
//   const v = uni.upx2px(750) - leftGap.value - rightGap.value - columnGap.value
//   const w = v/2
//   const rate = w / item.w
//   const h = rate* item.h
//   return {
//     width: w + 'px',
//     height: h + 'px'
//   }
// })
const changeList = (e: any) => {

  // if (e.name === 'list1') {
  //   list1.value.push(e.value)
  // } else if (e.name === 'list2') {
  //   list2.value.push(e.value)
  // }
}

// 骨架屏设置
const skeleton = ref([{
  type: 'line',
  num: 1,
  gap: '20rpx'
}])
const heightList_1 = ref<number[]>([])
const heightList_2 = ref<number[]>([])
const v = windowWidth - leftGap.value - rightGap.value - columnGap.value
const width = ref(v / 2)
/*console.log(v)
console.log(width.value)
const onLoadImage_1 = (data: any) => {
  // 确保 detailed.width 和 detailed.height 为有效数字
  const originalWidth = data.detail.width;
  const originalHeight = data.detail.height;

  // 计算缩放比例
  const scale = width.value / originalWidth;
  // 计算高度
  const height = (scale * originalHeight); // 使用 toFixed 保留两位小数

  // 需要确保计算出的高度是数字
  heightList_1.value.push(Number(height)); // 将其转换为数字并推入数组中
  console.log(Number(height)/width.value)
}
const onLoadImage_2 = (data: any) => {
  // 确保 detailed.width 和 detailed.height 为有效数字
  const originalWidth = data.detail.width;
  const originalHeight = data.detail.height;

  // 计算缩放比例
  const scale = width.value / originalWidth;

  // 计算高度
  const height = (scale * originalHeight); // 使用 toFixed 保留两位小数

  // 需要确保计算出的高度是数字
  heightList_2.value.push(Number(height)); // 将其转换为数字并推入数组中
}*/

// 收藏
const clickIndex = ref(0)
const userStore = useUserStore()
const delay = ref(false)
/**
 * 点击收藏
 * @param id 点击id
 * @param listIndex 点击list
 * @param index 点击列数的索引
 * @param like
 * @param type
 */
const onClickHeart = async (id: string, listIndex: number, index: number, like: 0 | 1, type?: 0 | 1) => {
  if (delay.value) {
    return
  }
  delay.value = true
  setTimeout(() => {
    delay.value = false
  }, 200)
  // 判断当前用户是否登录
  if (!userStore.userInfoData?.userID) {
    return uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
  }
  // 判断当前用户是否收藏
  addFavApi(Number(id), like === 0 ? 1 : 0, type).then(res => {
    if (res.code === '1') {
      if (listIndex === 0) {
        list.value[2 * index].isLike = like === 0 ? 1 : 0
      } else {
        list.value[2 * index + 1].isLike = like === 0 ? 1 : 0
      }
    }
  })
}


const originHeight_1 = ref()
const originHeight_2 = ref()
const getHeight = async () => {
  let height_1: number = 0
  let height_2: number = 0
  // 获取两个列表的高度
  uni.createSelectorQuery().select('.list1').boundingClientRect((data: any) => {
    height_1 = data.height
    if (height_1 === 0) return
    originHeight_1.value = height_1
  }).exec()
  uni.createSelectorQuery().select('.list2').boundingClientRect((data: any) => {
    height_2 = data.height
    if (height_2 === 0) return
    originHeight_2.value = height_2
  }).exec()
}
/**
 * 监听·props变化
 */
watch(props, () => {
  list.value = props.animalsList
  // getHeight()
}, {
  immediate: true
})

const heightDifference = computed(() => {
  return originHeight_1.value - originHeight_2.value
})
/*watch(heightDifference, () => {
  console.log('高度变化', heightDifference.value)
  console.log(list1.value.length)
  console.log(list2.value.length)
/!*  if (heightDifference.value > 100 || heightDifference.value < -100) {
    // 当前高度差明显需要手动调整高度差
    if (heightDifference.value > 100) {
      // 1、第一列高度过高,将最后一个元素给list2
      const pop = list1.value.pop()
      list2.value.push(pop!)
      console.log('第一列高度过高')
    } else if (heightDifference.value < -100) {
      // 2、第二列高度过高
      const pop = list2.value.pop()
      list1.value.push(pop!)
      console.log('第二列高度过高')
    } else {
      console.log('高度差正常')
    }
  }*!/
})*/
</script>

<template>
  <view :style="{paddingBottom:safeAreaInsets?.bottom+'px'}" class="animals-list-box">
    <!-- 标题名 -->
    <view class="list-title">
      <slot name="title">
      </slot>
    </view>
    <view class="animals-list">
      <!--    瀑布流  -->
      <view v-if="useWaterfall" class="waterfall flex justify-center" style="width: 100%;padding:0 5px">
        <uv-waterfall ref="waterfall"
                      v-model="list"
                      :add-time="10"
                      :column-gap="columnGap"
                      :left-gap="leftGap"
                      :right-gap="rightGap"
                      @changeList="changeList">
          <!-- 第一列数据 -->
          <template v-slot:list1>
            <!-- 为了磨平部分平台的BUG，必须套一层view -->
            <view class="list1">
              <view v-for="(item, index) in list1"
                    :key="item.id"
                    :style="{width:width+'px',height:item.h+'px',  background:hideText?'rgba(0,0,0,0)':'#fff'}"
                    class="waterfall-item">
                <view class="waterfall-item__image" @click="goDetail(item.id,item.type,item.img)"
                      @longpress="onLongPress(item)">
                  <view style="height: 100%;width: 100%">
                    <image v-if="item.img" :src="item.img" class="pic scale-up-center" fade-show="true"
                           lazy-load="true"
                           mode="widthFix">
                    </image>
                    <view v-else :style="{width:width+'px',height:'200px'}"
                          class="pic scale-up-center flex justify-center align-center flex-column padding-bottom-sm">
                      <image fade-show="true" lazy-load="true"
                             mode="aspectFit" src="/static/home-selected.png"
                             style="width: 80%">
                      </image>
                      <text class="text-gray">图片缺失</text>
                    </view>

                  </view>


                  <!--             图集标识     -->
                  <view v-show="item.type===1" :class="['picture', item.picNum>1?'cuIcon-album':'cuIcon-pic']"
                        style="font-size: 18px">
                    <text v-show="item.picNum>1" style="font-size: 14px">{{ item.picNum }}</text>
                  </view>

                  <!-- 收藏 -->
                  <view :class="[item.isLike?'heart-active':'']" class="heart-btn"
                        @click.stop="onClickHeart(item.id,0,index,item.isLike,item.type)">
                    <!-- 爱心 -->
                    <uv-icon :color="item.isLike?'#e3264e':'#abb7c3'" :name="'heart-fill'" size="26"></uv-icon>
                    <text :class="['d','heart',item.isLike?'active-d':'']"></text>
                  </view>

                </view>
                <view v-if="!hideText" class="waterfall-item__ft">
                  <view class="waterfall-item__ft__title">
                    <text class="value">{{ item.name }}</text>
                  </view>
                  <view class="waterfall-item__ft__desc desc">
                    <text class="value">{{ item.desc }}</text>
                  </view>
                </view>
              </view>
            </view>
          </template>
          <!-- 第二列数据 -->
          <template v-slot:list2>
            <!-- 为了磨平部分平台的BUG，必须套一层view -->
            <view class="list2">
              <view v-for="(item, index) in list2"
                    :key="item.id"
                    :style="{width:width+'px',height:item.h+'px',  background:hideText?'rgba(0,0,0,0)':'#fff'}"
                    class="waterfall-item">

                <view class="waterfall-item__image" @click="goDetail(item.id,item.type,item.img)"
                      @longpress="onLongPress(item)">

                  <view :style="{width:width+'px',height:item.h+'px'}">
                    <image v-if="item.img" :src="item.img" class="pic scale-up-center" lazy-load="true" mode="widthFix">
                    </image>
                    <view v-else :style="{width:width+'px',height:'200px'}"
                          class="pic scale-up-center flex justify-center align-center flex-column padding-bottom-sm">
                      <image fade-show="true" lazy-load="true"
                             mode="aspectFit" src="/static/home-selected.png"
                             style="width: 80%">
                      </image>
                      <text class="text-gray">图片缺失</text>
                    </view>
                  </view>


                  <!--             图集标识     -->
                  <view v-show="item.type===1" :class="['picture', item.picNum>1?'cuIcon-album':'cuIcon-pic']"
                        style="font-size: 18px">
                    <text v-show="item.picNum>1" style="font-size: 14px">{{ item.picNum }}</text>
                  </view>
                  <!-- 收藏 -->
                  <view :class="[item.isLike?'heart-active':'']" class="heart-btn"
                        @click.stop="onClickHeart(item.id,1,index,item.isLike,item.type)">
                    <!-- 爱心 -->
                    <uv-icon :color="item.isLike?'#e3264e':'#abb7c3'" :name="'heart-fill'" size="26"></uv-icon>
                    <text :class="['d','heart',item.isLike?'active-d':'']"></text>
                  </view>

                </view>
                <view v-if="!hideText" class="waterfall-item__ft" style="background: #FFFFFF">
                  <view class="waterfall-item__ft__title">
                    <text class="value">{{ item.name }}</text>
                  </view>
                  <view class="waterfall-item__ft__desc desc">
                    <text class="value">{{ item.desc }}</text>
                  </view>
                </view>
              </view>
            </view>
          </template>
        </uv-waterfall>
      </view>

      <!--   非瀑布流   -->
      <view v-else class="flex flex-wrap justify-between padding-lr-sm" style="width: 100%">
        <view v-for="(item,index) in animalsList " :key="item.id" class="list-item">

          <view class="flex flex-column align-center" style="width: 100%;height: 100%;"
                @click="goDetail(item.id,item.type,item.img)">
            <view class="pic scale-up-center" style="height: 85%; flex: 1;position: relative">
              <uv-image :lazy-load="true" :src="item.img" height="100%" mode="aspectFill" radius="8px" width="100%">
                <template v-slot:loading>
                  <view v-show="!item.img" class="flex flex-column justify-center align-center padding-bottom-sm"
                        style="width: 60%;height: 60%;overflow: hidden">
                    <uv-image :src="item.img?'/static/app-selected.png':'/static/error-img.png'" height="100%"
                              mode="aspectFit" width="100%"></uv-image>
                  </view>
                </template>
                <template v-slot:error>
                  <view class="flex flex-column justify-center align-center padding-bottom-sm"
                        style="width: 60%;height: 60%;overflow: hidden">
                    <uv-image :src="'/static/error-img.png'" height="100%" mode="aspectFit" width="100%"></uv-image>
                  </view>
                </template>
              </uv-image>
              <!--             图集标识     -->
              <view v-show="item.type===1" :class="['picture', item.picNum>1?'cuIcon-album':'cuIcon-pic']"
                    style="font-size: 18px">
                <text v-show="item.picNum>1" style="font-size: 14px">{{ item.picNum }}</text>
              </view>
              <view v-show="showPageView" class="page-view ">
                <uni-icons color="#fff" size="14" type="eye"></uni-icons>
                <text style="margin-left: 2px">{{ item.pageView }}</text>
              </view>
            </view>

            <view class="list-item-text">
              <rich-text v-if="showName" :nodes="item.name" class="name margin-tb-sm"></rich-text>
              <!--              <text  class="name margin-tb-sm">{{ item.name }}</text>-->
              <view v-if="!hideText&&item.type===0" style="margin-bottom: 5px">
                <uv-text :color="'#8d8d8d'" :lines="2" :text="item.desc ? item.desc : '简介暂无'" size="13"></uv-text>
              </view>
              <view v-else-if="!hideText&&item.type===1" class="flex flex-wrap" style="margin-bottom: 5px;gap: 8px">
                <view v-for="tag in item.tags!.split(',')" :key="tag">
                  <rich-text :nodes="'#'+tag" class="desc margin-tb-sm"></rich-text>
                </view>

              </view>
            </view>
          </view>

        </view>
      </view>

    </view>
    <view class="" style="height: 100rpx;width: 100%;padding-bottom: 200rpx">
      <slot name="footer"></slot>
    </view>
  </view>
</template>

<style lang="scss" scoped>

em {
  color: #39c5bb !important;
  font-style: normal !important;
}

.animals-list-box {
  display: flex;
  align-items: center;
  flex-direction: column;
  position: relative;
  padding-top: 0;

  .list-title {
    //margin-bottom: 5px;
  }

  .animals-list {
    width: 100%;

    .list-item {
      //overflow: hidden;
      display: flex;
      flex-direction: column;
      height: 230px;
      width: 48%;
      border: 1rpx solid #eee;
      margin-bottom: 20rpx;
      background: #FFFFFF;
      //padding-bottom: 10px;
      border-radius: 8px;

      .list-item-img {
        width: 100%;
        //height: 150px;
        //max-height: 400rpx;
        // 图像铺满
        object-fit: cover;
        border-radius: 10px;
      }

      .list-item-text {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: flex-start;
        padding: 0 10rpx;
        width: 100%;

        .name {
          font-size: 14px;
          font-weight: 600;
          //margin-top: 10rpx;
          color: #333;
        }
      }
    }
  }

  .desc {
    width: 100%;
    height: 60rpx;
    line-height: 30rpx;
    font-size: 12px;
    color: #8d8d8d;
    //text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    word-break: break-all;
    // 最多两行
    line-clamp: 2;
  }
}

$show-lines: 1;
@import '@/uni_modules/uv-ui-tools/libs/css/variable.scss';
.waterfall {
  width: 100%;
}

.waterfall-item {
  //overflow: hidden;
  margin-top: 10px;
  border-radius: 6px;
  background: #FFFFFF;
}

.waterfall-item__ft {
  padding: 10rpx 15rpx;
  background: #fff;
  border-radius: 0 0 10px 10px;

  &__title {
    margin-bottom: 10rpx;
    line-height: 48rpx;
    font-weight: 700;

    .value {
      font-size: 32rpx;
      color: #303133;
    }
  }

  &__desc .value {
    font-size: 26rpx;
    color: #606266;
  }

  &__btn {
    padding: 10px 0;
  }
}

.waterfall-item__image {
  position: relative;
}

.picTag {
  position: absolute; /* 绝对定位 */
  left: 5px;
  bottom: 5px;
  z-index: 1;
}

.picture {
  position: absolute; /* 绝对定位 */
  right: 5px;
  top: 5px;
  z-index: 1;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 5px;
  font-size: 16px;
  padding: 3px 5px;
  color: #FFFFFF;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 3px;
}

.page-view {
  position: absolute; /* 绝对定位 */
  left: 0px;
  bottom: 0px;
  z-index: 1;
  background: rgba(0, 0, 0, 0.4);
  border-radius: 0 5px 5px 5px;
  font-size: 12px;
  padding: 3px 5px;
  color: #FFFFFF;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 2px;
}

/* 按钮主体 */
.heart-btn {
  position: absolute; /* 绝对定位 */
  right: 5px;
  bottom: 5px;
  z-index: 1;
}

.heart-active { /* 切换后样式 */
  animation: beat .25s linear forwards;
}

.d {
  --c: #e3264e;
  z-index: 9;
  display: block;
  width: 6px;
  height: 6px;
  background-color: transparent;
  border-radius: 50%;
  /* 绝对定位 居中 */
  position: absolute;
  right: 5px;
  bottom: 5px;
  transform: translate(-50%, -50%) scale(0);
  /* 设置各个方向的阴影 */
  /* 通过var函数调用自定义属性--c,设置阴影颜色 */
  box-shadow: 0 -40px 0 var(--c), 0 40px 0 var(--c), -40px 0 0 var(--c),
  40px 0 0 var(--c), -30px -30px 0 var(--c), 30px -30px 0 var(--c),
  30px 30px 0 var(--c), -30px 30px 0 var(--c);
}

.active-d {
  /* 执行动画: 动画名 时长 加速后减速 停留在最后一帧 */
  animation: blink 0.5s ease-in-out forwards;
  /* 动画延迟时间 */
  animation-delay: 0.3s;
}

.pic {
  width: 100%;
  border-radius: 10px;
  background: #FFFFFF;
  box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
  overflow: hidden;
}

/* 心跳动的动画 */
@keyframes beat {
  0% {
    transform: scale(1);
  }
  40% {
    transform: scale(1.2);
  }
  60% {
    transform: scale(1.35);
  }
  80% {
    transform: scale(1.2);
  }
  90% {
    transform: scale(1.15);
  }
  100% {
    transform: scale(1);
  }
}

/* 小圆点闪出的动画 */
@keyframes blink {
  0% {
    transform: translate(-50%, -50%) scale(0.5);
    opacity: 0.8;
  }
  50% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(1.1);
    opacity: 0;
  }
}
</style>